package Text5;

import java.util.*;

public class Main {
    static int N = 210, n, m;
    static char[][] g = new char[N][N];
    static int[][] st = new int[N][N];
    static int[] dx = {-1, 1, 0, 0};
    static int[] dy = {0, 0, -1, 1};

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int T = in.nextInt();
        while (T-- > 0) {
            n = in.nextInt();
            m = in.nextInt();
            for (int i = 0; i < n; i++) {
                g[i] = in.next().toCharArray();
            }
            PII start = null, end = null;
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    if (g[i][j] == 'S') {
                        start = new PII(i, j);
                    }
                    if (g[i][j] == 'E') {
                        end = new PII(i, j);
                    }
                }
            }
            int ret = bfs(start, end);
            if (ret == -1) {
                System.out.println("oop!");
            } else {
                System.out.println(ret);
            }
        }
    }

    private static int bfs(PII start, PII end) {
        Queue<PII> q = new LinkedList<>();
        for (int i = 0; i < n; i++) {
            Arrays.fill(st[i], -1);
        }
        st[start.x][start.y] = 0;
        q.offer(start);
        while (!q.isEmpty()) {
            PII t = q.poll();
            for (int i = 0; i < 4; i++) {
                int x = t.x + dx[i];
                int y = t.y + dy[i];
                if (x < 0 || x >= n || y < 0 || y >= m) {
                    continue;
                }
                if (g[x][y] == '#') {
                    continue;
                }
                if (st[x][y] != -1) {
                    continue;
                }
                st[x][y] = st[t.x][t.y] + 1;
                if (x == end.x && y == end.y) {
                    return st[x][y];
                }
                q.offer(new PII(x,y));
            }
        }
        return -1;
    }
}

class PII {
    int x, y;

    public PII(int x, int y) {
        this.x = x;
        this.y = y;
    }
}